import 'package:flutter/material.dart';

class LifecycleDemo extends StatefulWidget {
  @override
  _LifecycleDemoState createState() => _LifecycleDemoState();
}

class _LifecycleDemoState extends State<LifecycleDemo>
    with WidgetsBindingObserver {
  AppLifecycleState? _lastLifecycleState;

  @override
  void initState() {
    super.initState();
    // 添加观察者
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    // 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _lastLifecycleState = state;
    });

    switch (state) {
      case AppLifecycleState.resumed:
        print('应用进入前台');
        _onResumed();
        break;
      case AppLifecycleState.inactive:
        print('应用非活动状态');
        break;
      case AppLifecycleState.paused:
        print('应用进入后台');
        _onPaused();
        break;
      case AppLifecycleState.detached:
        print('应用销毁');
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
        throw UnimplementedError();
    }
  }

  void _onResumed() {
    // 恢复动画、视频播放、定时器等
    print('执行恢复操作');
  }

  void _onPaused() {
    // 暂停耗电操作，保存数据等
    print('执行暂停操作');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('生命周期监听')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('当前状态:', style: TextStyle(fontSize: 20)),
            Text(
              '$_lastLifecycleState',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
